package com.flower.auth;

import cn.dev33.satoken.stp.StpInterface;

import com.alibaba.nacos.common.utils.StringUtils;
import com.flower.entity.AuthPermission;
import com.flower.entity.AuthRole;
import com.flower.redis.RedisUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lavender
 * @version 1.0
 * @date 2024-07-15 16:01
 *  自定义权限验证接口扩展
 */
@Component
public class StpInterfaceImpl implements StpInterface {


    @Resource
    private RedisUtil redisUtil;

    private String authPermissionPrefix = "auth.permission";

    private String authRolePrefix = "auth.role";


    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {




        return getAuth(authPermissionPrefix, loginId.toString());
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        return getAuth(authRolePrefix, loginId.toString());

    }



    private List<String> getAuth(String prefix, String loginId){
        String authKey = redisUtil.buildKey(prefix, loginId);

        String authValue = redisUtil.get(authKey);

        if (StringUtils.isBlank(authKey)) {
            return Collections.emptyList();
        }


        List<String> authList = new LinkedList<>();
        if(authRolePrefix.equals(prefix)){
            List<AuthRole> roleList = new Gson().fromJson(authValue, new TypeToken<List<AuthRole>>() {
            }.getType());
            authList = roleList.stream().map(AuthRole::getRoleKey).collect(Collectors.toList());

        }else if (authPermissionPrefix.equals(prefix)){
            List<AuthPermission> permissions = new Gson().fromJson(authValue, new TypeToken<List<AuthPermission>>() {
            }.getType());

            authList = permissions.stream().map(AuthPermission::getPermissionKey).collect(Collectors.toList());


        }


        return authList;

    }
}
